<?php

namespace app\api\controller\paotui;

use addons\paotui\service\Third;
use app\admin\model\paotui\Config;
use app\common\controller\Api;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\HttpException;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['oauthMiniUser'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }


    //小程序登录
    public function oauthMiniUser(){

        $configModel = new Config();
        $config = $configModel->where(['group'=>'mini'])->column("name,value");

        $code = $this->request->request("code");
        $options = [
            'app_id'   => $config['mini_appid'],
            'secret'   => $config['mini_appsecret'],
        ];

        try {
            $app = Factory::miniProgram($options);
            $sns = $app->auth->session($code);

            if(!empty($sns['openid'])){
                $result = [
                    'openid'        => $sns['openid'],
                    'nickname'      => "新用户"
                ];

                $loginret = Third::connect('miniapp', $result);

                if ($loginret) {
                    $userinfo = $this->auth->getUserinfo();
                    $data = [
                        'user_id'=> $userinfo['user_id'],
                        'token'  => $userinfo['token'],
                    ];
                    $this->success(__('Logged in successful'), $data);

                }else{
                    $this->error(Third::$error);
                }
            }else{
                $this->error(Third::$error);
            }
        }catch (HttpException $e){
            $this->error($e->getMessage());
        }

    }

    /**
     * 获取用户信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info(){
        $userModel = new \app\common\model\User();
        $userInfo = $userModel
            ->alias("user")
            ->join("paotui_user_level","user.id=paotui_user_level.user_id","left")
            ->join("paotui_level","paotui_user_level.level_id=paotui_level.id","left")
            ->where(['user.id'=>$this->auth->id])->field("user.id,user.nickname,user.avatar,user.mobile,paotui_level.level_name")->find();
        $this->success('请求成功',$userInfo);
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $nickname 昵称
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $mobile = $this->request->post('mobile');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $user->nickname = $nickname;
        $user->mobile = $mobile;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

}
